<template>
  <div class="bg-fff pd-10">
    <el-form class="form" ref="form" :model="form" :rules="rules" label-width="120px" label-position="right"
             size="small">
      <v-form-title title="账户信息"/>
      <el-form-item prop="accountNo" label="电票所在户">
        <div class="dfr">
          <div>
            <el-select v-model="form.accountNo" placeholder="请选择收款账户">
              <el-option
                      v-for="item in accounts"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value">
              </el-option>
            </el-select>
          </div>
          <span>
              银行卡号:{{form.accountNumber}}
           </span>
        </div>
        <span class="tips">请选择正确的收款账户,该户也将是回款账户</span>
      </el-form-item>
      <v-form-title title="上传票据图片"/>
      <div class="tips"><i class="iconfont icon-tishi"></i> 确保录入的票面信息与影像一致，最终票据信息以票据影像为准。</div>
      <el-form-item prop="imagesFront" label="票据正面">
        <v-bill-images v-model="form.imagesFront" :images="imagesFront" @change="testOcr"/>
      </el-form-item>
      <el-form-item prop="imagesBack" label="票据背面">
        <v-bill-images v-model="form.imagesBack" :images="imagesBack"/>
      </el-form-item>
      <p style="font-size: 16px; color: #666;text-align: center;">
        每次发布订单只能上传同一张票据的内容；允许上传的图片格式：jpg、jpeg、png、gif，图片大小不宜超过1.5M。</p>
      <v-form-title title="完善票面信息"/>
      <el-form-item prop="billType" label="票据类型">
        <el-radio-group v-model="form.billType">
          <el-radio-button :label="0">电票</el-radio-button>
          <el-radio-button :label="1">纸票</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="billNumber" label="票据号">
        <el-input class="line-input" v-model="form.billNumber" maxlength="30"/>
      </el-form-item>
      <el-form-item prop="acceptor" label="承兑人全称">
        <el-input class="line-input" v-model="form.acceptor"/>
      </el-form-item>
      <el-form-item prop="acceptorLineNumber" label="承兑人行号">
        <el-input class="line-input" v-model="form.acceptorLineNumber"/>
      </el-form-item>
      <el-form-item prop="acceptorType" label="承兑人类型">
        <el-radio-group v-model="form.acceptorType">
          <el-radio-button :label="1">国股</el-radio-button>
          <el-radio-button :label="2">城商</el-radio-button>
          <el-radio-button :label="3">三农</el-radio-button>
          <el-radio-button :label="4">村镇</el-radio-button>
          <el-radio-button :label="5">外资</el-radio-button>
          <el-radio-button :label="6">财务公司</el-radio-button>
          <el-radio-button :label="7">商票</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="faceValue" label="票面金额" class="has-unit">
        <el-input class="line-input" v-model="form.faceValue"/>
        <span class="unit">元</span>
      </el-form-item>
      <el-form-item prop="expiryDate" label="到期日">
        <el-date-picker
                class="line-input"
                v-model="form.expiryDate"
                placeholder="请选择到期日期"
                type="date"
                :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="endorsement" label="背书次数">
        <el-input-number v-model="form.endorsement" :min="1" :max="10"></el-input-number>
      </el-form-item>
      <div v-if="form.billType===1">
        <el-form-item prop="flaw" label="瑕疵情况">
          <el-checkbox-group v-model="form.flaw">
            <el-checkbox-button :label="1500">无瑕疵</el-checkbox-button>
            <el-checkbox-button :label="1501">回头背书</el-checkbox-button>
            <el-checkbox-button :label="1502">背书不清晰</el-checkbox-button>
            <el-checkbox-button :label="1503">书写不规范</el-checkbox-button>
            <el-checkbox-button :label="1504">骑缝章不规范</el-checkbox-button>
            <el-checkbox-button :label="1505">收背不符</el-checkbox-button>
            <el-checkbox-button :label="1506">重复背书</el-checkbox-button>
            <el-checkbox-button :label="1599">未知瑕疵</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item prop="backEndEndorsement" label="回头背书情况">
          <el-radio-group v-model="form.backEndEndorsement">
            <el-radio-button :label="0">无</el-radio-button>
            <el-radio-button :label="1">有</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="repeatEndorsement" label="重复背书情况">
          <el-radio-group v-model="form.repeatEndorsement">
            <el-radio-button :label="0">无</el-radio-button>
            <el-radio-button :label="1">有</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="pledgeEndorsement" label="质押背书情况">
          <el-radio-group v-model="form.pledgeEndorsement">
            <el-radio-button :label="0">无</el-radio-button>
            <el-radio-button :label="1">有</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </div>
      <el-form-item prop="canTransfer" label="能否转让">
        <el-radio-group v-model="form.canTransfer">
          <el-radio-button :label="1">可转让</el-radio-button>
          <el-radio-button :label="0">不可转让</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="biddingMethod" label="竞价方式">
        <el-radio-group v-model="form.biddingMethod">
          <el-radio-button :label="1">自由竞价</el-radio-button>
          <el-radio-button :label="0">一口价</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <div v-if="form.biddingMethod ===0">

        <el-form-item prop="annualInterestRate" label="年化利率" class="has-unit">
          <el-input class="line-input" v-model="form.annualInterestRate" @input="calc(false)"/>
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item prop="everyPlus" label="每十万扣款">
          <el-input class="line-input" v-model="form.everyPlus" @input="calc(true)"/>
        </el-form-item>
        <!--<el-form-item prop="billRate" label="贴现率" class="has-unit">-->
        <!--{{form.billRate}}-->
        <!--<span class="unit">%</span>-->
        <!--</el-form-item>-->
        <el-form-item prop="discountAmount" label="贴息额" class="has-unit">
          {{form.discountAmount}}
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item prop="transferAmount" label="转让额" class="has-unit">
          {{form.transferAmount}}
          <span class="unit">元</span>
        </el-form-item>
      </div>
      <el-form-item label="发布期限">
        <el-radio-group v-model="form.releaseDeadline">
          <el-radio-button :label="0">T + 0</el-radio-button>
          <el-radio-button :label="1">T + 1</el-radio-button>
          <el-radio-button :label="2">T + N</el-radio-button>
        </el-radio-group>
        <el-input-number v-model="form.releaseDeadline" :min="2" :max="10"
                         v-if="form.releaseDeadline > 1"></el-input-number>
      </el-form-item>

    </el-form>
    <div class="operation">
      <el-button type="primary" @click="valid(0)">上传票据并发起融资</el-button>
      <el-button type="primary" plain @click="valid(1)">上传到票据库存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator'

  import vFormTitle from '@/components/form-title'
  import vBillImages from '@/components/bill-images'
  import { Action } from 'vuex-class'

  @Component({
    components: {
      vFormTitle,
      vBillImages
    }
  })
  export default class Single extends Vue {
    @Action getPolicy

    form = {
      imagesFront: [{}],
      imagesBack: [{}, {}, {}],
      billType: 0,
      billNumber: '',
      acceptorLineNumber: '',
      acceptorType: 1,
      acceptor: '',
      faceValue: '',
      expiryDate: '',
      endorsement: 1,
      canTransfer: 1,
      biddingMethod: 1,
      backEndEndorsement: 0,
      releaseDeadline: 0,
      flaw: [1500],
      transferAmount: 0,
      discountAmount: 0,
      annualInterestRate: '',
      everyPlus: '',
      billRate: '',
      repeatEndorsement: 0,
      pledgeEndorsement: 0,
      billEveryDeduction: '',
      accountNo: '',
      accountNumber: '',
      calculationMethod: ''
    }
    rules = {
      imagesFront: [{ type: 'array', required: true, message: '请上传票据正面图片', trigger: 'change', len: 1 }],
      imagesBack: [{ type: 'array', required: true, message: '请上传票据背面图片', trigger: 'change', min: 1 }],
      flaw: [{ type: 'array', required: true, message: '请上传票据背面图片', trigger: 'change', min: 1 }],
      billType: [{ required: true, message: '请选择票据类型', trigger: 'change' }],
      billNumber: [{ required: true, message: '请输入票据号', trigger: 'change' }],
      acceptor: [{ required: true, message: '请输入承兑人全称', trigger: 'change' }],
      acceptorLineNumber: [{ required: true, message: '请输入承兑人行号', trigger: 'change' }],
      acceptorType: [{ required: true, message: '请选择承兑人类型', trigger: 'change' }],
      faceValue: [{ required: true, message: '请输入票面金额', trigger: 'change' }],
      endorsement: [{ required: true, message: '请输入背书次数', trigger: 'change' }],
      expiryDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
      canTransfer: [{ required: true, message: '请选择能否转让', trigger: 'change' }],
      biddingMethod: [{ required: true, message: '请选择竞价方式', trigger: 'change' }],
      releaseDeadline: [{ required: true, message: '请输入发布期限', trigger: 'change' }],
      backEndEndorsement: [{ required: true, message: '请选择背书情况', trigger: 'change' }],
      repeatEndorsement: [{ required: true, message: '请选择背书情况', trigger: 'change' }],
      pledgeEndorsement: [{ required: true, message: '请选择背书情况', trigger: 'change' }],
      accountNo: [{ required: true, message: '请选择收款账户', trigger: 'change' }]
    }
    imagesFront = [
      {
        src: '',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/2fe37b23-3a99-4aee-9d56-ba08169e19ab.png',
        key: 'billFrontView',
        name: '票据正面'
      }
    ]
    imagesBack = [
      {
        src: '',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/39df04f1-c017-4b00-a151-e34989f7b568.png',
        key: 'billEndorsementOne',
        name: '票据背面'
      },
      {
        src: '',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/39df04f1-c017-4b00-a151-e34989f7b568.png',
        key: 'billEndorsementTwo',
        name: '票据背面2'
      },
      {
        src: '',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/39df04f1-c017-4b00-a151-e34989f7b568.png',
        key: 'billEndorsementThree',
        name: '票据背面3'
      }
    ]
    accounts: ProductTypes[] = []

    valid (releaseType) {
      if (this.form.canTransfer === 0) {
        this.$notify.error('不可转让的票无法进行融资')
        return
      }
      this.$refs.form.validate(v => {
        if (v) {
          let f = { ...this.form }
          f['billFrontView'] = f.imagesFront[0].src
          f.imagesBack.forEach(item => {
            f[item.key] = item.src
          })
          f.releaseType = releaseType
          f.enterpriseUserId = JSON.parse(window.sessionStorage.getItem('userInfo')).user
          f.expiryDate = +new Date(f.expiryDate)
          if (f.billType === 0) {
            delete  f.flaw
          } else {
            delete f.backEndEndorsement
          }
          delete  f.imagesBack
          delete  f.imagesFront
          this.publishBill(f)
        }
      })
    }

    async publishBill (f) {
      // console.log(f)
      // console.log(this.form)
      // if(f.calculationMethod === null || f.calculationMethod === undefined) {
      //   // f.calculationMethod =
      // }
      let res: AjaxResponse = this.$route.query.id ? await this.$axios.put('g/gateway/bill/resubmit', f) : await this.$axios.post('g/gateway/bill/add', f)
      this.$utils.tips(res)
      if (res.responseCode === 200) {
        this.$router.push('/transaction/inventory')
      }
    }

    async testOcr (images) {
      let res: AjaxResponse = await this.$axios.post('g/gateway/ocr/bill', {
        imageUrl: images[0].src
      })
      if (res.responseCode === 200) {
        this.form.acceptor = res.data.acceptor_bank
        this.form.billNumber = res.data.bill_number
        this.form.acceptorLineNumber = res.data.acceptor_cnaps
        // @ts-ignore
        this.form.expiryDate = +new Date(res.data.deadline_time)
        this.form.faceValue = parseInt(res.data.bill_sum_price).toString() || ''
      }
    }
    data () {
      return {
        pickerOptions0: {
          disabledDate(time) {
              return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    }
    mounted () {
      this.getPolicy()
      this.getBankAccount()
      if (this.$route.query.id) {
        this.platForm(this.$route.query.id)
      }

    }

    async platForm (id) {
      let res: AjaxResponse = await this.$axios.get(`b/boms/bill/${id}`)
      for (let key in this.form) {
        if (this.form.hasOwnProperty(key) && res.data.hasOwnProperty(key)) {
          this.form[key] = res.data[key]
        }
      }
      this.imagesFront[0].src = res.data.billFrontView
      this.form.imagesFront[0].src = res.data.billFrontView
      this.form.imagesFront[0].key = 'billFrontView'

      this.imagesBack[0].src = res.data.billEndorsementOne
      this.imagesBack[1].src = res.data.billEndorsementTwo
      this.imagesBack[2].src = res.data.billEndorsementThree

      this.form.imagesBack[0].src = res.data.billEndorsementOne
      this.form.imagesBack[0].key = 'billEndorsementOne'
      this.form.imagesBack[1].src = res.data.billEndorsementTwo
      this.form.imagesBack[1].key = 'billEndorsementTwo'
      this.form.imagesBack[2].src = res.data.billEndorsementThree
      this.form.imagesBack[2].key = 'billEndorsementThree'
      this.form.id = res.data.id
      this.form.everyPlus = res.data.billEveryDeduction
      this.form.calculationMethod = res.data.calculationMethod
    }

    getResByAdjInterestRate () {
      return this.$axios.post('g/gateway/calculator/calculate', {
        interestRate: this.form.annualInterestRate,
        faceValue: this.form.faceValue,
        expiryDate: +new Date(this.form.expiryDate),
        adjustDay: this.form.billType === 0 ? 0 : 3
      })
    }

    getResByEveryPlus () {
      return this.$axios.post('g/gateway/calculator/everyplus', {
        everyPlus: this.form.everyPlus,
        faceValue: this.form.faceValue,
        expiryDate: +new Date(this.form.expiryDate),
        adjustDay: this.form.billType === 0 ? 0 : 3
      })
    }

    async calc (isEveryPlus) {
      // console.log(isEveryPlus)
      let res = await (isEveryPlus ? this.getResByEveryPlus() : this.getResByAdjInterestRate())
      if (isEveryPlus) {
        this.form.discountAmount = res.data.discountAmount
        this.form.transferAmount = res.data.transferAmount
        this.form.billEveryDeduction = res.data.billEveryDeduction
        this.form.annualInterestRate = res.data.interestYear
        this.form.billRate = res.data.billRate
        this.form.calculationMethod = '1'
      } else {
        this.form.discountAmount = res.data.discountAmount
        this.form.transferAmount = res.data.transferAmount
        this.form.billEveryDeduction = res.data.billEveryDeduction
        this.form.everyPlus = res.data.everyPlus
        this.form.billRate = res.data.billRate
        this.form.calculationMethod = '0'
      }
    }

    async getBankAccount () {
      let userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'))
      let res: AjaxResponse = await
        this.$axios.get(`g/gateway/account/user/${userInfo.userId}`)
      this.accounts = res.data.map(v => {
        return {
          value: v.id,
          label: v.bankName,
          accountNumber: v.accountNumber
        }
      })
      this.form.accountNo = this.accounts[0].value.toString()
      this.form.accountNumber = this.accounts[0].accountNumber.toString()
    }
  }
</script>

<style lang="less" scoped>
  .bg-fff {
    margin-top: 10px;
  }

  .form {
    width: 1180px;
    margin: 0 auto;
    height: 100%;
    padding-top: 20px;
  }

  .operation {
    margin-top: 50px;
    text-align: center;
  }

  .dfr {
    > * {
      width: 50%;
    }
    > span {
      font-size: 14px;
      color: #606266;
      line-height: 40px;
      padding: 0 12px 0 0;
      box-sizing: border-box;
    }
  }

  .tips {
    background: #F2F6F9;
    color: #999999;
    padding-left: 10px;
    line-height: 24px;
    margin-bottom: 10px;
    .iconfont {
      color: #F55205;
    }
  }

  .has-unit {
    position: relative;
    .unit {
      position: absolute;
      top: 0;
      left: 142px;
      color: #333;
    }
  }

  .tips {
    color: red;
  }
</style>
